<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace backend\filters;

use Yii;
use yii\base\ActionFilter;
class RbacFilter extends ActionFilter
{
    public function beforeAction($action)
    {
        // 获取用户状态
        $session = Yii::$app->session;
        $admin_id = $session->get('admin_id');
        if(!$admin_id)
        {
            return $this->redirect(array('site/login'));
        }
        if($admin_id == 1)
        {//顶级权限
            return parent::beforeAction($action);
        }
        //获取用户的角色权限
        $query = (new \yii\db\Query())
            ->select(['p.controller_name','p.action_name'])
            ->from('privilege as p')
            ->leftJoin('privilegecollect as pc',"pc.pri_id = p.id and pc.type = 1 and pc.is_usable = 1")
            ->leftJoin('adminrole as ar',"ar.role_id = pc.quote_id")
            ->where(['ar.admin_id'=>$admin_id,'p.is_usable' => 1])
            ->all();
        $c = Yii::$app->controller->id;
        $a = Yii::$app->controller->action->id;
        foreach($query as $k=>$v)
        {
            if($v['controller_name'] == $c && $v['action_name'] == $a)
            {
                return parent::beforeAction($action);
            }
        }
        $session->setFlash('pri_error','您无权限访问！');
        echo '
        <div style="color:red;">您无权限访问,3s后跳回首页!</div>
        <script type="text/javascript">
                    window.onload=function(){
                    setTimeout(go, 3000); 
                        }; 
        function go(){
            location.href="index.php";
        } 
        </script> ';exit;
        return false;
    }

}
